$(function(){
	/**
	 * @desc 商品信息
	 */
	var global_product = {
			'page': $_GET['page'] ? $_GET['page'] : undefined,//页码
			'pageSize' : $_GET['pageSize'] ? $_GET['pageSize'] : undefined, //页数
			'name': undefined,//商品名称
	}
	var global_count = 1;
	var select_units;
	//时间
	dateSelFun($('#instore_time'));
	
	/**
	 * @desc 单位
	 * 
	 */
	(function(){
		select_units = '<select class="form-control units"><option value="0">请选择单位..</option>';
		loading()
		$.get('list-units', function(data, status){
			removeloading();
			if(status =='success' && data.Ack =='Success'){
				var U = data.Body;
				for(var i in U){
					select_units +='<option value="'+U[i].unit_id+'">'+U[i].unit_name+'</option>';
				}
			}
			select_units +='</select>';
		});
	
	})();
	//新增仓库
	$('#addWarehouse').on('click',function(){
		$('#myWarehouse').modal('show');
	})
	//仓库
	$('#warehouse_save').on('click', function() {
		$warehouse = $('#warehouse_name').val();
		if ($warehouse.length == 0) {
			alertTips('warning','请输入仓库名')
			return false;
		}
		var pflag = 0;
		$remark = $('#remark').val();
		$default = $('#default').prop('checked');
		$wid = $('#warehouse_save').attr('data-wid');
		loading();
		$.get('save-warehouse', {
			'name' : $warehouse,
			'remark' : $remark,
			'def' : $default,
			'wid' : $wid
		}, function(data, status) {
			removeloading();
			if (status === 'success' && data.Ack == 'Success') {
				alertTips('success','保存成功');
				setTimeout(function() {
					$('#myWarehouse').modal('hide');
				}, 1000);
			} else if (data.Error == "warehouse is exists") {
				alert('warning','该仓库已经存在，请更改仓库名称');
				return false;
			} else {
				alertTips('error','网络错误');
				return false;
			}
		})
	});
	
	
	
	
	//添加供应商
	$('#addSupplier').on('click',function(){
//		$('#myWarehouse').modal('show');
		//新开窗口
		window.open("/supplier/create-supplier");       
	})
	
	/**
	 * @desc 选择商品
	 */
	$('#instore_detail').on('click','.search-product',function(){
		$('#productName').val('');
		getProducts();
		
	})
	//过滤商品
	$('#searchProduct').on('click', function() {
		var _name = trim($('#productName').val());
		global_product.name = _name;
		getProducts();
		return;
	})
	
	/**
	 * @desc 查询商品
	 */
	function getProducts(pageInfo){
		if (pageInfo !== undefined) {
			global_product.page = pageInfo.page;
			global_product.pageSize = pageInfo.pageSize;
		}
		$('#product_list').find('tr').remove();
		loading();		
		 $.ajax({
             url: 'get-products',
             type: "GET",
             cache: true,
             data: global_product,
             dataType: "json",
             jsonp: "callback",
             global:false,
             success: function(data){
            	 removeloading();
            	 var P = data.Body.list;
					if(P && P.length){
						for(var i in P){
							$('<tr>'
							+'<td class="text-center">'+(+i+1)+'</td>'
							+'<td class="text-center id">'+P[i].product_id+'</td>'
							+'<td class="text-center name">'+P[i].product_name+'</td>'
							+'<td class="text-center sn">'+P[i].product_sn+'</td>'
							+'<td class="text-center quantity">'+P[i].quantity+'</td>'
							+'<td class="text-center unit" data-unit="'+P[i].quantity_unit+'">'+P[i].unit_name+'</td>'
							+'<td class="text-center"><a href="javascript:void(0)" class="product_select">选择</a></td>'
							+'</tr>').appendTo('#product_list');
			              
						}
						var pageInfo = data.Body.page;
			            if (typeof pageInfo !== 'undefined'){
			              	refreshPaginationNavBar2($('.paginationNavBar'), pageInfo.page, pageInfo.pageSize, data.Body.count, getProducts);
			            }
					}else {
						$('<tr><td colspan="5" class="text-center">没有数据</td></tr>').appendTo('#product_list');
						refreshPaginationNavBar2($('.paginationNavBar'), 1, 10, 1, getProducts);
					}
				$('#chooseProduct').modal('show');//选择商品窗口
             }
		 })
	}
	
	//添加商品
	$('#product_list').on('click','.product_select',function(){
		var tr =$(this).closest('tr');
		var id = tr.find('.id').text();
		var name = tr.find('.name').text();
		var sn = tr.find('.sn').text();
		var quantity = tr.find('.quantity').text();
		var unit = tr.find('.unit').data('unit');
		var unit_name = tr.find('.unit').text();
		if(global_count == 1){
			var pid = $('#stockList').find('.stock-minus-tr').data['id'];
			if(pid == undefined){
				//刚开始添加数据
				$('#stockList').find('tr:first').remove();
			} ;
		}
		var units = '<select class="form-control" disabled><option selected value="'+unit+'">'+unit_name+'</option></select>';
		$('<tr>'
		  +'<td class="text-center">'+global_count+'</td>'
		  +'<td class="text-center"><a href="javascript:void(0)"class="stock-minus-tr" data-id="'+id+'"> <i class="fa fa-minus-circle" style="color:red;" ></i></a></td>'
		  +'<td class="text-center" name="name" data-id="'+id+'"><input title="商品名称" type="text" value="'+name+'"'
		  +'class="product-name stock-input50"  style="height: 30px;width:80%"> <a class="search-btn search-product" title="搜索"'
		  +'href="javascript:void(0)"><i class="fa fa-search"></i></a></td>'
		  +'<td class="text-center" name="sn">'+sn+'</td>'
		  +'<td class="text-center" name="quantity"><input type="text"></td>'
		  +'<td class="text-center" name="unit">'+units+'</td>'
		  +'<td class="text-center" name="remark"><input type="text" style="width:100%;"></td>'
		  +'<td class="text-center"><a href="javascript:void(0)" class="checkStock" data-quantity="'+quantity+'">库存</a></td>'
		  +'</tr>').appendTo('#stockList');
		global_count++;
	})
	
	//删除数据
	$('#stockList').on('click','.stock-minus-tr',function(){
		if(global_count == 1){
			return false;
		} else if(global_count == 2){
			//添加一条数据要删除数据 后插入一条空数据
			$('#stockList').find('tr:first').remove();
			global_count--;
			insertOrginHtml();
			return false;
		} else {
			var self = $(this);
			//判断当前要删除的行,下面是否还有记录
            var nextTr = self.parent().parent().next('tr');
            if(nextTr.length){
            	//存在下一行，清空当前行数据
                self.closest('tr').remove();
                // 序号重新排列
                var td = $('#stockList').find('tr').find('td:first');
                $.each(td, function(index, item) {
                    var item = $(item);
                    item.text(index+1);
                })
                global_count--;
                return false;
            } else{
            	//删除的为最后一行
                self.closest('tr').remove();
                global_count--;
                return false;
            }
		}
		
	});
	
	var insertOrginHtml = function(){
		$('<tr>'
				  +'<td class="text-center">'+global_count+'</td>'
				  +'<td class="text-center"><a href="javascript:void(0)"class="stock-minus-tr" data-id=""> <i class="fa fa-minus-circle" style="color:red;" ></i></a></td>'
				  +'<td class="text-center" name="name" data-id=""><input title="商品名称" type="text" value=""'
				  +'class="product-name stock-input50"  style="height: 30px;width:80%"> <a class="search-btn search-product" title="搜索"'
				  +'href="javascript:void(0)"><i class="fa fa-search"></i></a></td>'
				  +'<td class="text-center" name="sn"></td>'
				  +'<td class="text-center" name="quantity"><input type="text"></td>'
				  +'<td class="text-center" name="unit">'+select_units+'</td>'
				  +'<td class="text-center" name="remark"><input type="text" style="width:100%;"></td>'
				  +'<td class="text-center"><a href="javascript:void(0)" class="checkStock">库存</a></td>'
				  +'</tr>').appendTo('#stockList');
	}
	//库存提示
	$('#stockList').on('click','.checkStock',function(){
		var _quantity = $(this).attr('data-quantity');
		layer.tips('库存: '+ _quantity, $(this), {
			  tips: [4, '#78BA32']
		});
	});

	(function() {
		// 保存
		$('#save').on('click', function() {
			//单头
			var head = instore_header();
			if(!head){
				return false;
			}
			//明细
			var detail = instore_detail();
			if(!detail){
				return false;
			}
			var ii = layer.load();
			$.get('save-instore',{'head':head,'det':detail}, function(data,status){
				setTimeout(function(){
					  layer.close(ii);
				}, 1000);
				if(status =='success'){
					if(data.Ack =='Success'){
						alertTips('success','保存成功');
					}
				} else {
					alertShows('error','网络错误');
				}
			})
		});

	})();	

	var instore_header = function() {
		var no = $('#instore_no').val();
		var origin_type = $('#instore_type').val();
		var instore_time = $('#instore_time').val();
		if (instore_time.length == 0) {
			alertTips('warning', '请输入入库时间');
			return false;
		}
		var warehouse = $('#warehouse').val();
		if (!+warehouse) {
			alertTips('warning', '请选择入库仓库');
			return false;
		}
		var handle_man = $('#handle_man').val();
		if (!+handle_man) {
			alertTips('warning', '请选择入库人员');
			return false;
		}
		var vendor = $('#vendor').val();
		if (!+vendor) {
			alertTips('warning', '请输入供应商');
			return false;
		}
		var remark = $('#remark').val();
		var create_man = $('#create_man').attr('data-id');
		var instore_head = {
			'instore_no' : no,
			'instore_type' : origin_type,
			'instore_date' : instore_time,
			'warehouse_id' : warehouse,
			'instore_man' : handle_man,
			'vendor_id' : vendor,
			'create_man' : create_man,
			'remark' : remark
		};
		return instore_head;
	}
	
	//入库单明细
	var instore_detail = function(){
		var product_det=[];
		var product_info = [];
		var _tr = $('#stockList').find('tr');
		var flag = 1;
		if(_tr.length == 1){
			var pid = _tr.first('tr').find('td[name="name"]').attr('data-id');
			if(pid == ''){
				alertTips('warning','请选择商品');
				return false;
			}
		}
		_tr.each(function(index,element){
			var tr = $(this);
			var quantity = tr.find('[name="quantity"] input').val();
			if(quantity == ''){
				alertTips('warning','请填写数量');
				flag = 0;
				return false;
			}
			product_det = {
				'goods_id':tr.find('[name="name"]').attr('data-id'),
				'quantity': quantity,
				'unit': tr.find('[name="unit"] select').val(),
				'remark': tr.find('[name="remark"] input').val(),
			};
			product_info.push(product_det);
			product_det = [];
		});
		if(!flag){
			return false;
		}
		if(product_info.length == 0){
			alertTips('warning','请选择产品！');
			return false;
		}
		return product_info;
	}
	

});




